// api/api.go
package api

import (
	"bytes"
	"device_manager/config"
	"device_manager/models"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"time"
)

// 通用请求函数
func sendRequest(url string, payload map[string]interface{}) (map[string]interface{}, error) {
	jsonData, err := json.Marshal(payload)
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 15 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var result map[string]interface{}
	err = json.NewDecoder(resp.Body).Decode(&result)
	if err != nil {
		return nil, err
	}

	if code, ok := result["code"].(float64); ok && code != 0 {
		return result, errors.New(result["msg"].(string))
	}

	return result, nil
}

// 门禁开门
func OpenDoor(device *models.Device, cfg *config.Config) error {
	url := "https://wdev.wmj.com.cn/deviceApi/send"
	payload := map[string]interface{}{
		"app_id":     cfg.AppID,
		"app_secret": cfg.AppSecret,
		"device_sn":  device.DeviceSN,
		"type":       1,
		"data": map[string]interface{}{
			"cmd_type": "open",
			"info": map[string]interface{}{
				"delay": 1500,
			},
		},
	}
	_, err := sendRequest(url, payload)
	return err
}

// 电源空开：开电
func TurnOnPower(device *models.Device, cfg *config.Config) error {
	url := "https://wdev.wmj.com.cn/deviceApi/send"
	payload := map[string]interface{}{
		"app_id":     cfg.AppID,
		"app_secret": cfg.AppSecret,
		"device_sn":  device.DeviceSN,
		"time_out":   15,
		"data": map[string]interface{}{
			"cmd_type": "turnon",
			"info":     map[string]interface{}{},
		},
	}
	_, err := sendRequest(url, payload)
	return err
}

// 电源空开：关电
func TurnOffPower(device *models.Device, cfg *config.Config) error {
	url := "https://wdev.wmj.com.cn/deviceApi/send"
	payload := map[string]interface{}{
		"app_id":     cfg.AppID,
		"app_secret": cfg.AppSecret,
		"device_sn":  device.DeviceSN,
		"type":       1,
		"data": map[string]interface{}{
			"cmd_type": "turnoff",
		},
	}
	_, err := sendRequest(url, payload)
	return err
}

// 电源空开：查询用电情况
func GetPowerInfo(device *models.Device, cfg *config.Config) (map[string]interface{}, error) {
	url := "https://wdev.wmj.com.cn/deviceApi/send"
	payload := map[string]interface{}{
		"app_id":     cfg.AppID,
		"app_secret": cfg.AppSecret,
		"device_sn":  device.DeviceSN,
		"type":       1,
		"data": map[string]interface{}{
			"cmd_type": "getdevinfo",
		},
	}
	result, err := sendRequest(url, payload)
	if err != nil {
		return nil, err
	}
	if data, ok := result["data"].(map[string]interface{}); ok {
		if info, ok := data["info"].(map[string]interface{}); ok {
			return info, nil
		}
	}
	return nil, fmt.Errorf("无法解析返回的数据")
}

// 云喇叭：播放云语音
func PlayCloudVoice(device *models.Device, cfg *config.Config, tts string) error {
	url := "https://wdev.wmj.com.cn/deviceApi/send"
	payload := map[string]interface{}{
		"app_id":     cfg.AppID,
		"app_secret": cfg.AppSecret,
		"device_sn":  device.DeviceSN,
		"type":       1,
		"data": map[string]interface{}{
			"cmd_type": "play",
			"info": map[string]interface{}{
				"tts":    tts,
				"volume": 3,
			},
		},
	}
	_, err := sendRequest(url, payload)
	return err
}

// 云喇叭：循环播放云语音
func LoopPlayCloudVoice(device *models.Device, cfg *config.Config, tts string) error {
	url := "https://wdev.wmj.com.cn/deviceApi/send"
	payload := map[string]interface{}{
		"app_id":     cfg.AppID,
		"app_secret": cfg.AppSecret,
		"device_sn":  device.DeviceSN,
		"type":       1,
		"data": map[string]interface{}{
			"cmd_type": "loop_play",
			"info": map[string]interface{}{
				"tts":      tts,
				"interval": 45,
			},
		},
	}
	_, err := sendRequest(url, payload)
	return err
}
